import React from "react";
import { useState, useEffect } from "react";
import storage from "../Storage/Storage";

function Todos() {
  const [list, setlist] = useState([
    {
      title: "PHP",
      isck: false,
    },
    {
      title: "React",
      isck: true,
    },
  ]);
  useEffect(() => {
    function getStorage(key) {
      //读取缓存
      let data = storage.getStorage("lists");
      //第一次刷新的时候，data不存在，给list赋值以后,map无法遍历，因此在这里需判断data是否存在
      if (data) {
        setlist(data);
      }
    }
    return () => {
      function removeStorage(key) {
        localStorage.removeItem(key);
      }
    };
  }, [list]);
  //回车事件
  function keyEnter(e) {
    if (e.which === 13) {
      let ele = e.target;
      // console.log(ele.value);
      let listinfo = {
        title: ele.value,
        isck: false,
      };
      let newlist = [...list];
      newlist.push(listinfo);
      setlist(newlist);
      ele.value = "";
      storage.setStorage("lists", newlist);
    }
  }
  //监听事件
  function changeBox(index) {
    let data = [...list];
    data[index].isck = !data[index].isck;
    console.log(data[index]);
    setlist(data);
    storage.setStorage("lists", data);
  }
  //删除事件
  function deleteData(index) {
    let data = [...list];
    data.splice(index, 1);
    setlist(data);
  }
  return (
    <div className="block">
      <div className="title">
        <div className="titleleft">
          <h2>ToDoList</h2>
        </div>
        <div className="titleright">
          <input type="text" onKeyPress={(e) => keyEnter(e)} />
        </div>
      </div>
      <hr />
      <div>
        <ul>
          <h3>未完成</h3>
          {list.map((v, k) => {
            if (!v.isck) {
              return (
                <div key={k}>
                  <li>
                    <input
                      type="checkbox"
                      checked={v.isck}
                      onChange={() => changeBox(k)}
                    />
                    {v.title}--------
                    <button onClick={() => deleteData(k)}>删除</button>
                  </li>
                </div>
              );
            }
            return "";
          })}
          <h3>已完成</h3>
          {list.map((v, k) => {
            if (v.isck) {
              return (
                <div key={k}>
                  <li>
                    <input
                      type="checkbox"
                      checked={v.isck}
                      onChange={() => changeBox(k)}
                    />
                    {v.title}--------
                    <button onClick={() => deleteData(k)}>删除</button>
                  </li>
                </div>
              );
            }
            return "";
          })}
        </ul>
      </div>
    </div>
  );
}

export default Todos;
